<template>
    <div class="sticky" :fixed="fixed">
        <div class="sticky-normal" ref="normal">
            <slot />
        </div>
        <div class="sticky-fixed" :style="style">
            <slot />
        </div>
    </div>
</template>
<script>
export default {
    name: "CommonSticky",
    props: {
        top: { type: Number, default: 0 },
        scroll: { type: Number, default: 0 },
    },
    data () {
        return {
            fixed: false,
            style: null,
        };
    },
    methods: {

        setFixed (fixed, rect) {
            this.fixed = fixed;
            if (this.fixed) {
                this.style = {
                    left: rect.left + 'px',
                    width: rect.width + 'px',
                    height: rect.height + 'px',
                    top: this.top + 'px',
                }
            } else {
                this.style = null;
            }

        },


        onScroll (event) {
            const elem = this.$el.querySelector('.sticky-normal')
            const rect = elem ? elem.getBoundingClientRect() : null;
            if (rect && this.top > rect.y) {
                !this.fixed && this.setFixed(true, rect);
            } else {
                this.fixed && this.setFixed(false);
            }
        },
    },

    mounted () {
        window.addEventListener('scroll', this.onScroll)
        window.addEventListener('resize', this.onScroll)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.onScroll)
        window.removeEventListener('resize', this.onScroll)
    }
};
</script>
<style lang="scss" scoped>
.sticky-fixed {
    position: fixed;
    display: none;
    z-index: 1;
}

.sticky[fixed] {
    // position: relative;
    .sticky-normal {
        opacity: 0;
        pointer-events: none;
    }
    .sticky-fixed {
        display: block;
    }
}
</style>
